import { ProgressBar, Vec2 } from 'cc';
import { find, Sprite, SpriteFrame,tween,Tween,Game,game as gameCCD, _decorator, Component, Label, Node ,Vec3, Animation } from 'cc'
import { App } from '../../../App';
import { EventConst } from '../../../common/Common';
import { loadCommonPreFab, showGameActionPoint, showGameMulitExit, showScoreParticle } from '../../../tools/PopuUp';
import UtilTool from '../../../tools/UtilTool';
import { EnergyBar } from '../EnergyBar';
import { GameBaseModel } from '../GameBaseModel';
import { ACTION_POINT_R, BLOOD_PLAYDRAGON_ANIM, FOUR_BALL_BASE, GAME_HITBALL_TIME, SYSTEM_ADDRESS } from '../GameManage';
import { GameModel5 } from './GameModel5';
import { GameBloodUser } from './GameBloodUser';
import { MultiRule } from '../../../hall/multiplay/MultiRule';
import { PD } from '../../../player/PlayerData';
import { Prefab } from 'cc';
import { instantiate } from 'cc';
import { Role } from '../Role';
import { GameBloodRoleScore } from './GameBloodRoleScore';
import GameConst from '../../../const/GameConst';
import wsTool from '../../../net/ws';
import { GameBaseLogic } from '../GameBaseLogic';
import { UITransform } from 'cc';
const { ccclass, property } = _decorator;

// 游戏2D界面
@ccclass('GameLayer5')
export class GameLayer5 extends Component {
    @property(Node)
    bg_fight : Node = null

    @property(Node)
    roleScoreParent : Node = null

    @property(Node)
    djsNode : Node = null

    @property(Label)
    timeLabel : Label = null

    @property(Label)
    changeScore : Label = null

    @property(ProgressBar)
    timeProgressBar1 : ProgressBar = null

    @property(ProgressBar)
    timeProgressBar2 : ProgressBar = null

    @property(Prefab)
    roleScorePrefab : Prefab = null

    // 倒计时剩余时间
    private countdown = 0
    // 左边玩家地址
    public leftUserAddress = ""
    // 右边玩家地址
    public rightUserAddress = ""
    // 底分
    public anteScore = 0
    // 洞分节点
    public roleScoreNode = []

    public ballScore = null // 球得分
    public holdScore = null // 球洞得分
    public areaScore = null // 区域得分
    public isEndScoreEff = false // 是否结束了金币粒子动画

    onLoad() {
    //     gameCCD.on(Game.EVENT_HIDE, function(){
    //         if (this.node==null) return
    //         if(!this.isBackGround){
    //             this.isBackGround = true;
    //             UtilTool.printLog("切换后台");
                
    //         }
    //     }.bind(this));
    //     gameCCD.on(Game.EVENT_SHOW, function(){
    //         if (this.node==null) return
    //         if(this.isBackGround){
    //             UtilTool.printLog("切换前台");    
    //             this.isBackGround = false;
    //             this.reqGameData()
    //         }
    //     }.bind(this));
    }

    start() {
        let gameView = App.Model.gameView as GameModel5
        gameView.setHoleSwitch(true)

        // this.setCurrentPlayer()
        this.setTimeAction(-1)
        this.UpdataScore({})
        this.setUIView([])

        this.setActionPoint(new Vec2(0,0))
        //更新作用点位置
        App.Event.on(EventConst.ACTION_BALL_POINT,(data)=>{
            this.setActionPoint(data)
        },this)

        // 倒计时
        this.djsNode.active = false

        // 设置底分
        if (App.Model.gameManage.gameStartBloodData.bloodLevel == 0 ) {
            this.anteScore = PD.bloodConfig.apprenticeBaseScore
        }
        else if (App.Model.gameManage.gameStartBloodData.bloodLevel == 1) {
            this.anteScore = PD.bloodConfig.masterBaseScore
        }
        this.UpdataAnteScore()


        // 在节点里面添加球洞分数预制件
        for (let i = 0; i < 6; i++) {
            if (this.roleScorePrefab) { 
                let node = instantiate(this.roleScorePrefab);
                this.roleScoreParent.addChild(node);
                node.active = false
                this.roleScoreNode.push(node)
            }
        }
        setTimeout(() => {
            let roleNodeList = gameView.roleNodeList
            for (let i = 0; i < roleNodeList.length; i++) {
                let item = roleNodeList[i]
                let itemCtrl = item.getComponent(Role)
                if (item && itemCtrl) {
                    if (this.roleScoreNode[i]) {
                        let roleScoreCtrl = this.roleScoreNode[i].getComponent(GameBloodRoleScore)
                        let localPos = gameView.World3DToLocal(item.worldPosition)
                        this.roleScoreNode[i].setPosition(localPos.x, localPos.y)
                        roleScoreCtrl.init(itemCtrl.roleNumber)
                    }
                }
            }
        }, 100)
    }

    update(deltaTime: number) {
        
    }

    /**
     * 更新双方分数
     */
    UpdataScore(scoreData) {
        let myScore=0, otherScore=0
        for (const key in scoreData) {
            if (Object.prototype.hasOwnProperty.call(scoreData, key)) {
                const data = scoreData[key];
                if (key==this.leftUserAddress) {
                    myScore = data
                }
                else{
                    otherScore = data
                }
            }
        }

        let coinLabel1 = find("mtNode/coinLabel",this.bg_fight).getComponent(Label)
        let coinLabel2 = find("otherNode/coinLabel",this.bg_fight).getComponent(Label)
        let coinSpr1 = find("mtNode/coinSpr",this.bg_fight)
        let coinSpr2 = find("otherNode/coinSpr",this.bg_fight)
        coinLabel1.string = UtilTool.formatValue(myScore,{digit:1,type:2})
        coinLabel2.string = UtilTool.formatValue(otherScore,{digit:1,type:2})

        UtilTool.adaptiveLabel([coinLabel1.node, coinSpr1],0 ,6)
        UtilTool.adaptiveLabel([coinLabel2.node, coinSpr2],0 ,6)
    }

    /**
     * 更新底分
     * @param ballScore 球得分
     * @param holdScore 球洞得分
     * @param areaScore 区域得分
     */
    UpdataAnteScore(ballScore=null, holdScore=null, areaScore=null, isEnd = false) {
        // if (this.isEndScoreEff) return

        // this.isEndScoreEff = isEnd
        if (ballScore || holdScore || areaScore) {
            if (this.ballScore == -PD.bloodConfig.whiteBallInHoleDeductScore) return
            
            if (ballScore){ // 球得分
                if (this.ballScore){
                    this.ballScore = this.ballScore + ballScore
                }
                else{
                    this.ballScore = ballScore
                }

                // 白球进洞，分数都重置
                if (ballScore == -PD.bloodConfig.whiteBallInHoleDeductScore){
                    this.ballScore = -PD.bloodConfig.whiteBallInHoleDeductScore
                    // UtilTool.printLog("cjw 动画5",this.ballScore)
                    holdScore = null
                    areaScore = null
                    this.holdScore = null
                    this.areaScore = null

                    this.changeScore.string = this.ballScore + ""
                    return
                }
            }
            
            if (holdScore){ // 球洞得分
                if (this.holdScore){
                    this.holdScore = this.holdScore + holdScore
                }
                else{
                    this.holdScore = holdScore
                }
            }
            if (areaScore){ // 区域得分
                if (this.areaScore){
                    this.areaScore = this.areaScore + areaScore
                }
                else{
                    this.areaScore = areaScore
                }
            }

            // 赋值
            let scoreStr = this.anteScore + "x("
            if (this.ballScore) {
                scoreStr = scoreStr + "" + this.ballScore
            }
            if (this.holdScore) {
                scoreStr = scoreStr + "+" + this.holdScore
            }
            if (this.areaScore) {
                scoreStr = scoreStr + "+" + this.areaScore
            }
            this.changeScore.string = scoreStr + ")"
        }
        else{
            // 重置
            this.ballScore = null
            this.holdScore = null
            this.areaScore = null
            this.changeScore.string = this.anteScore + ""
            // UtilTool.printLog("cjw 动画6",this.ballScore)
        }
        
    }

    /**
     * 更新洞分数
     */
    UpdataRoleScore(holeScoreMap) {
        for (let index = 0; index < this.roleScoreNode.length; index++) {
            let node = this.roleScoreNode[index];
            let roleScoreCtrl = node.getComponent(GameBloodRoleScore)
            roleScoreCtrl.updateView(holeScoreMap)
        }
    }

    /**
     * 设置当前击打玩家动画
     */
    setCurrentPlayer(address = SYSTEM_ADDRESS) {
        // this.timeProgressBar1.node.active = address==this.leftUserAddress
        // this.timeProgressBar2.node.active = address!=this.leftUserAddress

        // if (address==this.leftUserAddress){

        // }
        // else if (address==SYSTEM_ADDRESS){
        // }
        // else{

        // }
    }

    /* 设置UI界面 */
    setUIView(allUserObj:GameBloodUser[]) {
        let myAddress = find("mtNode/address",this.bg_fight).getComponent(Label)
        let otherAddress = find("otherNode/address",this.bg_fight).getComponent(Label)

        myAddress.node.active = allUserObj.length>0
        otherAddress.node.active = allUserObj.length>0
        if (allUserObj.length>0) {
            for (let index = 0; index < allUserObj.length; index++) {
                let item = allUserObj[index];

                // 设置左边玩家的归属
                let inLeft = false
                if (item.mine) {
                    inLeft = true
                }

                if (inLeft) {
                    this.leftUserAddress = item.userAddress
                    myAddress.string = UtilTool.formatNickOrAddress({"nickname":item.userNickname, "address":item.userAddress})
                }
                else{
                    this.rightUserAddress = item.userAddress
                    otherAddress.string = UtilTool.formatNickOrAddress({"nickname":item.userNickname, "address":item.userAddress})
                }
            }
        }
    }

    /**
     * 设置倒计时动画
     * @param countdown 剩余倒计时时间 秒
     */
    setTimeAction(countdown=0, currentHitPlayer = SYSTEM_ADDRESS) {
        this.timeProgressBar1.progress = 0
        this.timeProgressBar2.progress = 0
        this.djsNode.active = false
        if (countdown==-1) {
            return
        }

        let timeProgressBar: ProgressBar = null
        if (currentHitPlayer==this.leftUserAddress){
            timeProgressBar = this.timeProgressBar1
        }
        else{
            timeProgressBar = this.timeProgressBar2
        }
        timeProgressBar.progress = countdown/GAME_HITBALL_TIME
        

        this.countdown = countdown
        UtilTool.timeCountdown3(this.timeLabel, countdown, (type,time=0)=>{
            if (type==1) {
                this.countdown = time

                if (this.countdown<=10 ) {
                    if (!this.djsNode.active) {
                        this.djsNode.active = true
                    }
                    // 播放倒计时声音
                    App.Audio.playOneShot("timeDJS")
                }

                timeProgressBar.progress = this.countdown/GAME_HITBALL_TIME

                if (this.countdown <=1) {
                    // 时间倒计时还剩1秒的时候不能请求击球
                    let gameView = App.Model.gameView as GameModel5
                    if (gameView) {
                        gameView.cueCtrl.isHitBall = false
                    }
                }
            }
            else if (type==2) {

            }
        },2) 
    }

    /**
     * 停止倒计时
     */
    stopTimeSchedule() {
        Tween.stopAllByTarget(this.timeLabel.node)
        this.djsNode.active = false
        // this.setCurrentPlayer()
    }

    /**
     * 播放金币飞向赢家的动画
     */
    playScoreToWinerAnim() {
        if(App.Model.gameLogic==null) return

        let allScore = 0 // 总分数
        if (this.ballScore!=null) {
            allScore = allScore + this.ballScore
        }
        if (this.holdScore!=null) {
            allScore = allScore + this.holdScore
        }
        if (this.areaScore!=null) {
            allScore = allScore + this.areaScore
        }

        // UtilTool.printLog("cjw 动画4",this.ballScore,this.holdScore,this.areaScore)
        if (allScore==0) return

        // 动画起始、结束位置
        let startPos = new Vec2(0, 0)
        let endPos = new Vec2(0, 0)

        // 当前玩家是否是左边的
        let gameLogic = App.Model.gameLogic as GameBaseLogic
        let gameView = App.Model.gameView as GameModel5
        let curPlayer = gameLogic.curPlayUser
        let isLeft = curPlayer.userAddress==this.leftUserAddress 

        // 位置计算转换
        let leftPos = find("mtNode",this.bg_fight).getPosition()
        let rightPos = find("otherNode",this.bg_fight).getPosition()
        let leftPos_w = this.bg_fight.getComponent(UITransform).convertToWorldSpaceAR(leftPos)
        let rightPos_w = this.bg_fight.getComponent(UITransform).convertToWorldSpaceAR(rightPos)
        leftPos_w = UtilTool.UIPosToLocalPos(leftPos_w)
        rightPos_w = UtilTool.UIPosToLocalPos(rightPos_w)
        // 位置赋值
        let func_pos = (posx_1,posy_1,posx_2,pos_2)=>{
            startPos.x = posx_1
            startPos.y = posy_1
            endPos.x = posx_2
            endPos.y = pos_2
        }
        if (isLeft) {
            if (allScore>0) {
                func_pos(rightPos_w.x, rightPos_w.y, leftPos_w.x, leftPos_w.y)
            }
            else{
                func_pos(leftPos_w.x, leftPos_w.y, rightPos_w.x, rightPos_w.y)
            }
        }
        else{
            if (allScore>0) {
                func_pos(leftPos_w.x, leftPos_w.y, rightPos_w.x, rightPos_w.y)
            }
            else{
                func_pos(rightPos_w.x, rightPos_w.y, leftPos_w.x, leftPos_w.y)
            }
        }

        // 计算显示变化金币总数，并播放变化金币的放大效果
        if (allScore<0) {
            this.changeScore.string = allScore + ""
        }
        else{
            this.changeScore.string ="+" + this.anteScore * allScore 
        }
        tween(this.changeScore.node)
            .to(0.3, {scale: new Vec3(1.7,1.7,1.0)})
            .to(0.3, {scale: new Vec3(1.0,1.0,1.0)})
            .start()


        // 金币粒子动画
        App.Audio.playOneShot("game/moreCoin")
        showScoreParticle({
            "startPos":startPos,
            "endPos":endPos,
            "type":2,
            "func":()=>{
            },
        },gameView.effNode)

        if (allScore>0) { // 达到一定的分数，会享受播放龙动画的无上荣耀
            let gameView = App.Model.gameView as GameModel5
            gameView.playDragonAnim(allScore)
        }
    }

    // 重置进度条
    resetProgress() {
        find("energyBar",this.node).getComponent(EnergyBar).resetProgress()
    }

    protected onDestroy(): void {
        App.Event.off(EventConst.ACTION_BALL_POINT, this.setActionPoint, this)
    }

    /** 
     * 点击作用点
      */
    clickActionPoint() {
        // if (App.Model.gameManage.isWatchGame) {
        //     // 观战模式不能点击设置作用点
        //     return
        // }

        let gameView = App.Model.gameView as GameBaseModel
        showGameActionPoint(gameView.viewNode)
    }

    /** 
     * 设置作用点
      */
    setActionPoint(pos) {
        let ratio = 50 / ACTION_POINT_R
        let point = find("actionBall/redpoint",this.node)
        point.setPosition(pos.x * ratio, pos.y * ratio)

        if (pos.x == 0 && pos.y == 0) {
            App.Model.gameManage.ballActionDial = 0
            App.Model.gameManage.setActionPoint(pos)
            App.Event.emit(EventConst.GAME_HIT_ACTIONVIEW)
        }
    }

    // 显示规则
    async onBtnQuestion() {
        App.Audio.playOneShot("click")
        // let node = await loadCommonPreFab("prefabs/hall/multiplay/multiRule", null)
        // node.getComponent(MultiRule).setGameType(1)

        // wsTool.send({msgCode:GameConst.Req_GIVEUP})
        // .then((data) => {
        //     if(data.result == 0) {
        //         UtilTool.printLog("认输成功")
        //     } else {
        //         UtilTool.printLog("认输失败", data.result)
        //     }
        // })

        let gameView = App.Model.gameView as GameModel5
        gameView.playDragonAnim(18)

    }

}

